<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\Controller;
use App\Models\Forward;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException; // 引入 ValidationException
use Illuminate\Support\Facades\Http;

class ForwardController extends Controller
{
    public function add(Request $request)
    {
        $user = auth()->user();

        if (admin_setting('domain_add_check')) {
            $domain = $request->input('domain');
            $verificationString = substr(md5(env('APP_KEY')), 0, 20);
            $data = @file_get_contents('http://' . $domain . '/api/domain/verify');
            if ($data!=$verificationString and isset($data)) {
                return response()->json(['status' => '0', 'msg' => '检测失败，请检查您的域名是否已成功解析到我们的服务器']);
                
            } 
            
        }
        // 检查用户的转发额度
        if ($user->forward < 1) {
            return response()->json(['status' => '0', 'msg' => '转发额度不足']);
        }

        try {
            // 验证 domain 和 url 字段不能为空，并确保 domain 唯一
            $validatedData = $request->validate([
                'domain' => 'required|unique:forward', // 添加唯一性验证
                'url' => 'required',
            ], [
                'domain.required' => '域名不能为空',
                'domain.unique' => '该域名已被使用', // 自定义唯一性错误信息
                'url.required' => '目标地址不能为空',
            ]);
        } catch (ValidationException $e) {
            // 捕获验证异常并返回 JSON 格式的错误信息
            $errors = $e->errors();
            foreach ($errors as $field => $errorMessages) {
                $msg = reset($errorMessages);
                break; // 只取第一个错误信息
            }

            return response()->json(['status' => '0', 'msg' => $msg], 422);
        }

        // 获取表单数据
        $domain = $request->input('domain');
        $mode = $request->input('mode');
        $url = $request->input('url');
        $title = $request->input('title');
        $keywords = $request->input('keywords');
        $description = $request->input('description');
        if (admin_setting('audit') == 1) {
            $status = 0;
        } else {
            $status = 1;
        }

        // 保存表单数据，并显式添加 created_at 和 updated_at 字段
        Forward::create([
            'uid' => $user->id, // 添加用户ID
            'domain' => $domain,
            'mode' => $mode,
            'status' => $status,
            'url' => $url,
            'title' => $title,
            'keywords' => $keywords,
            'description' => $description,
            'created_at' => now(), // 添加创建时间
            'updated_at' => now(), // 添加更新时间
        ]);

        // 减少用户的转发额度
        $user->forward -= 1;
        $user->save();

        return response()->json(['status' => '1', 'msg' => '添加成功']);
    }
    public function edit(Request $request, $id)
    {
        $user = auth()->user();
        $forward = Forward::where('uid', $user->id)->where('id', $id)->first();
        if (!$forward) {
            return response()->json(['status' => '0', 'msg' => '想干啥！飘了？']);
        }
        $data=[
            'url' => $request->input('url'),
            'title' => $request->input('title'),
            'description' => $request->input('description'),
            'keywords' => $request->input('keywords'),
            'updated_at' => now(), 
            'mode' => $request->input('mode'),];
        $forward->update($data);
        return response()->json(['status' => '1', 'msg' => '更新成功']);
        
    }
    public function del($id)
    {
        $forward = Forward::where('id', $id)->where('uid', auth()->user()->id)->first();
        if (!$forward) {
            return response()->json(['status' => '0', 'msg' => '想干啥！飘了？']);
        }
        $forward->delete();
        return response()->json(['status' => '1', 'msg' => '删除成功']);
    }
    public function get($id)
    {
    }
    public function verify(Request $request)
    {
        $verificationString =  substr(md5(env('APP_KEY')), 0, 20);
        return $verificationString;
    }
}
